package com.fanrui.code.chess.mahjong;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.fanrui.code.chess.mahjong.round.MahjongOperationResponse;
import com.fanrui.code.mahjong.util.MahjongCardUtil;
import com.fanrui.proto.cmd.MahjongGroup;
import com.fanrui.proto.cmd.MahjongGroup.GroupType;
import com.fanrui.proto.cmd.Operation;
import com.fanrui.proto.cmd.ResPlayerOperation.Result;
import com.google.protobuf.MessageLite;

public class CanHostingGamer extends MahjongGamer {

	protected int executeDefaultNum = 0;

	public CanHostingGamer(int id, long playerId, int tableId, String ip, double x, double y) {
		super(id, playerId, tableId, ip, x, y);
	}

	@Override
	public void notifyResponse(MahjongOperationResponse response, int waitTime) {
		if ((response.getType() == Operation.TOUCH && response.getOperationId() != getPlayerID())
				|| (response.getType() == Operation.PENG && response.getOperationId() != getPlayerID())
				|| (response.getType() == Operation.CHI && response.getOperationId() != getPlayerID())) {
			return;
		}
		currendResponse = response;
		List<Mahjong> cards = MahjongCardUtil.getInstance().clone(getHandCards());

		if (response.getType() == Operation.SEND) {
			cards.add(response.getCard());
		}
		if (getHosting()) {
			waitTime = 3;
		}
		if (waitTime > 0) {
			if (this.waitTime == null) {
				this.waitTime = new AtomicInteger(waitTime);
			} else {
				this.waitTime.set(waitTime);
			}

		}
		System.out.println("玩家" + getGamerID() + "收到通知" + response + "ss" + this.waitTime.get());
	}

	public void trick() {
		if (waitTime != null) {
			if (waitTime.get() <= 0) {
				doDefaultOperation();
			} else {
				waitTime.decrementAndGet();
			}
		}

	}

	public void doDefaultOperation() {
		if (currendResponse != null) {
			AbstractMahjongTable<?> table = getTable();
			if (table == null) {
				return;
			}
			executeDefaultNum++;
			canHost();
			if (currendResponse.getType() == Operation.CHI) {
				if (currendResponse.getOperationId() == getPlayerID()) {
					MahjongOperationResponse response = new MahjongOperationResponse();
					response.setCard(findUnUsedCard());
					response.setOperationId(getPlayerID());
					response.setType(Operation.SEND);
					Result result = table.addPlayerResponse(response);
					if (result == Result.Success) {
						clearWaitOperatoion();
						table.playerSuccessCallResponse();
						return;
					} else {
						try {
							throw new IllegalAccessException("出牌失败：" + result);
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
					}
				}
			}
			
			if (currendResponse.getType() == Operation.PENG) {
				if (currendResponse.getOperationId() == getPlayerID()) {
					MahjongOperationResponse response = new MahjongOperationResponse();
					response.setCard(findUnUsedCard());
					response.setOperationId(getPlayerID());
					response.setType(Operation.SEND);
					Result result = table.addPlayerResponse(response);
					if (result == Result.Success) {
						clearWaitOperatoion();
						table.playerSuccessCallResponse();
						return;
					} else {
						try {
							throw new IllegalAccessException("出牌失败：" + result);
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						}
					}
				}
			}

			if (currendResponse.getType() == Operation.TOUCH) {
				if (!handCards.isEmpty()) {
					if (table != null) {
						MahjongOperationResponse response = new MahjongOperationResponse();
						Mahjong operationCard = currendResponse.getCard();
						response.setOperationId(getPlayerID());
						if (this.checkHu(operationCard)) {
							if (operationCard == null) {// 在第一局就自摸 随机张牌 天胡
								operationCard = handCards.get(0);
							}
							response.setCard(operationCard);
							response.setType(Operation.ZIMO);
						} else if (canAnGang(operationCard)) { // 这种写法很容易就造成不能操作
																// 有待改进
							List<Mahjong> anGangList = MahjongCardUtil.getInstance().get4Card(handCards, null);
							if (anGangList != null && anGangList.size() > 0) {
								operationCard = anGangList.get(0);
							}
							response.setCard(operationCard);
							response.setType(Operation.GANG_A);

						} else if (canBnGang(operationCard)) {
							response.setCard(operationCard);
							response.setType(Operation.GANG_B);

						} else {
							response.setCard(findUnUsedCard());
							response.setType(Operation.SEND);
						}
						Result result = table.addPlayerResponse(response);
						if (result == Result.Success) {
							clearWaitOperatoion();
							table.playerSuccessCallResponse();
							return;
						} else {
							try {
								throw new IllegalAccessException("出牌失败：" + result);
							} catch (IllegalAccessException e) {
								e.printStackTrace();
							}
						}
					}
				}

			}
			// 其他人出牌
			if (currendResponse.getType() == Operation.SEND) {
				MahjongOperationResponse response = new MahjongOperationResponse();
				response.setOperationId(getPlayerID());
				Mahjong card = currendResponse.getCard();
				response.setCard(card);
				int num = MahjongCardUtil.getInstance().getCardNumFromHand(card, handCards);

				if (checkHu(card)) {
					response.setType(Operation.BOOM);
				} else if (checkGang(card) && num >= 3) {
					response.setType(Operation.GANG_M);
				} else if (checkPeng(card) && haveWeighOperation(card, Operation.PENG)) {
					response.setType(Operation.PENG);
				} 
//				else if (checkEat(card)) {
//					// 找到玩家手牌的可以吃的两张牌
//					
//					
//					response.setType(Operation.EAT);
//				} 
				else {
					response.setType(Operation.GUO);
				}
				Result result = table.addPlayerResponse(response);
				if (result == Result.Success) {
					clearWaitOperatoion();
					table.playerSuccessCallResponse();
					return;
				}
			}
		}
		if (checkReady()) {
			// if (!isReady() && !getLeave()) {
			clearWaitOperatoion();
			AbstractMahjongTable<?> table = getTable();
			table.playerReady(this);
			return;
		}
		
		
//		if (currendResponse != null) {
//			AbstractMahjongTable<?> table = getTable();
//			if (table == null) {
//				return;
//			}
//			executeDefaultNum++;
//			canHost();
//			
//			if (currendResponse.getType() == Operation.PENG) {
//				if (currendResponse.getOperationId() == getPlayerID()) {
//					MahjongOperationResponse response = new MahjongOperationResponse();
//					response.setCard(findUnUsedCard());
//					response.setOperationId(getPlayerID());
//					response.setType(Operation.SEND);
//					Result result = table.addPlayerResponse(response);
//					if (result == Result.Success) {
//						clearWaitOperatoion();
//						table.playerSuccessCallResponse();
//						return;
//					} else {
//						try {
//							throw new IllegalAccessException("出牌失败：" + result);
//						} catch (IllegalAccessException e) {
//							e.printStackTrace();
//						}
//					}
//				}
//			}
//
//			if (currendResponse.getType() == Operation.TOUCH) {
//				if (!handCards.isEmpty()) {
//					if (table != null) {
//						MahjongOperationResponse response = new MahjongOperationResponse();
//						response.setOperationId(getPlayerID());
//						response.setCard(findUnUsedCard());
//						response.setType(Operation.SEND);
//						Result result = table.addPlayerResponse(response);
//						if (result == Result.Success) {
//							clearWaitOperatoion();
//							table.playerSuccessCallResponse();
//							return;
//						} else {
//							try {
//								throw new IllegalAccessException("出牌失败：" + result);
//							} catch (IllegalAccessException e) {
//								e.printStackTrace();
//							}
//						}
//					}
//				}
//
//			}
//			// 其他人出牌
//			if (currendResponse.getType() == Operation.SEND) {
//				MahjongOperationResponse response = new MahjongOperationResponse();
//				response.setOperationId(getPlayerID());
//				Mahjong card = currendResponse.getCard();
//				response.setCard(card);
//				response.setType(Operation.GUO);
//				Result result = table.addPlayerResponse(response);
//				if (result == Result.Success) {
//					clearWaitOperatoion();
//					table.playerSuccessCallResponse();
//					return;
//				}
//			}
//		}
//		if (checkReady()) {
//			clearWaitOperatoion();
//			AbstractMahjongTable<?> table = getTable();
//			table.playerReady(this);
//			return;
//		}
	}

	private void canHost() {
		// TODO Auto-generated method stub
		
	}

	public boolean checkReady() {
		return false;
	}

	/**
	 * 
	 * 找出一张最不需要的牌 评分最低的牌
	 * 
	 * @return MahjongCard
	 */
	public Mahjong findUnUsedCard() {
		return handCards.get(0);
	}

	@Override
	public void notifyStart() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public MessageLite toCmd(long playerId) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public boolean canAnGang(Mahjong card) {
		if (MahjongCardUtil.getInstance().getCardNumFromHand(card, handCards) >= 4 && !isHu) {
			return true;
		} else {
			return false;
		}
	}

	public boolean canBnGang(Mahjong card) {
		if (group != null) {
			for (MahjongGroup mg : group) {
				if (mg.getType() == GroupType.PENG && mg.getMjsCount() > 0 && card.cardEquals(mg.getMjs(0))) {
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 检查是否能杠
	 * 
	 * @return boolean
	 */
	public boolean checkGang(Mahjong card) {
		if (card == null) {
			return false;
		}
		int num = MahjongCardUtil.getInstance().getCardNumFromHand(card, handCards);
		if (num >= 3) {
			return true;
		} else if (group != null) {
			for (MahjongGroup mahjongGroup : group) {
				if (mahjongGroup.getType() == GroupType.PENG && mahjongGroup.getMjsCount() >= 0) {
					com.fanrui.proto.cmd.Mahjong mahjong = mahjongGroup.getMjs(0);
					if (mahjong.getType() == card.getType() && mahjong.getNumber() == card.getNumber()) {
						return true;
					}
				}
			}
			return false;
		} else {
			return false;
		}
	}
	
	public boolean checkPeng(Mahjong card) {
		if (card == null) {
			return false;
		}
		if (MahjongCardUtil.getInstance().getCardNumFromHand(card, handCards) >= 2 && !isHu) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 有没有操作的必要 在碰或杠的时候 进行判断
	 * 
	 * @return boolean
	 */
	public boolean haveWeighOperation(Mahjong card, Operation operation) {
		// 当前的总评分
		int currentTotal = MahjongCardUtil.getInstance().expectMarking(handCards, group, null, null, false, true, getTable().getGameRules());
		int operaionedTotal = MahjongCardUtil.getInstance().expectMarking(handCards, group, card, operation, false,false,getTable().getGameRules());// 碰了牌之后 可以听的牌 被减分了 所以这里改成false
		return currentTotal <= operaionedTotal;
	}
}
